package com.qf.smsplatform.search.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smsplatform.common.enums.SmsEnum;
import com.qf.smsplatform.common.exception.SmsException;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * projectName: sms-platform
 *
 * @author: 黄睿武
 * time: 2021/8/23 16:43
 * description:  es的搜索实现类
 */

@Service
@Slf4j
public class ElasticSearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //将对象json化
    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 添加submit到es的索引中
     *
     * @param submit
     */
    @Override
    public void index(StandardSubmit submit) throws IOException {

        //1.创建request对象
        IndexRequest request = new IndexRequest();

        //2.封装request对象
        request.index("sms_submit_log_" + this.getYear());
        request.id(submit.getSequenceId());
        request.source(objectMapper.writeValueAsString(submit), XContentType.JSON);

        //3.发送request对象获取response对象
        IndexResponse resp = restHighLevelClient.index(request, RequestOptions.DEFAULT);

        //4.基于Response对象判断添加是否成功
        if(!resp.getResult().getLowercase().equals("created")){
            log.info("[搜索模块-写日志] 写日志操作失败 !!! result = {},submit = {}",resp.getResult().toString(),submit);
            throw new SmsException(SmsEnum.ERROR);
        }
        log.info("[搜索模块-写日志] 写日志操作成功 !!");
    }

    private String getYear(){
        return new SimpleDateFormat("yyyy").format(new Date());
    }
}
